package com.nulldev.util.uri.iwebkit2;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.nulldev.util.java.swing.canvas.PaintMethod;
import com.nulldev.util.java.swing.canvas.SmoothCanvas;
import com.nulldev.util.java.swing.font.FontManager;
import com.nulldev.util.uri.iwebkit2.document.Document;
import com.nulldev.util.uri.iwebkit2.document.Element;
import com.nulldev.util.uri.iwebkit2.fonts.WebKitFontManager;
import com.nulldev.util.uri.iwebkit2.fonts.WebKitFontManager.Fonts;
import javax.swing.JScrollPane;

public class iWebKit2Renderer extends JFrame {

	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(final Document doc) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					FontManager.loadSystemSpecificFonts();
					iWebKit2Renderer frame = new iWebKit2Renderer(doc);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public iWebKit2Renderer(final Document doc) {
		setTitle("iWebKit2");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 823, 488);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		final SmoothCanvas panel = new SmoothCanvas() {
			
			private int lastY = 0;
			private int lastX = 0;
			
			@Override
			public void drawCanvas(Graphics2D g2d) {
				int y = 15;
				for (final Element element : doc.cloneRenderableElements()) {
					final Font font = WebKitFontManager.getFontFor(Fonts.parse(element.getAttribute("font", "sans-serif")));
					g2d.setFont(font);
					final int rSize = g2d.getFontMetrics().stringWidth(element.getInnerHTML());
					if (rSize > lastX) {
						this.lastX = rSize;
					}
					g2d.drawString(element.getInnerHTML(), 5, y);
					y += 15;
				}
				this.lastY = y;
			}
			
			@Override
			public Dimension getPreferredSize() {
				return new Dimension(this.lastX + 10, this.lastY);
			}
		};
		scrollPane.setViewportView(panel);
		panel.setAAEnabled(true);
		panel.usePaintMethod(PaintMethod.REPAINT);
		panel.setFPS(60);
	}

}
